package com.ray.auth.system.service.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.flyong.cache.query.cache.CacheConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ray.auth.system.service.DictService;
import com.ray.auth.system.table.entity.Dict;
import com.ray.auth.system.table.entity.DictExample;
import com.ray.auth.system.table.entity.DictExample.Criteria;
import com.ray.auth.system.table.mapper.DictMapper;
import com.xiaoleilu.hutool.util.StrUtil;
import com.zjhc.flyhong.common.function.enums.DeleteEnum;
import com.zjhc.flyhong.common.function.exception.BussinessException;
import com.zjhc.flyhong.common.function.operator.LoginUser;
import com.zjhc.flyhong.common.function.operator.PageDto;
import com.zjhc.flyhong.common.function.validate.EntityValidate;
import com.zjhc.flyhong.common.function.validate.rule.FieldRule;
import com.zjhc.flyhong.common.function.validate.rule.RuleEnum;
import com.zjhc.flyhong.common.util.UUIDUtil;
import com.zjhc.flyhong.common.web.ErrorMsg;
import com.zjhc.flyhong.common.web.Result;
import com.zjhc.flyhong.common.web.ResultHelper;
import com.zjhc.flyhong.common.web.SuccessMsg;
import com.zjhc.flyhong.common.web.base.BaseService;
/**
 * <h1>系统权限应用  字典  服务实现</h1>
 * @创建人 ray
 * @创建时间 2017-06-10
 * @版本 1.0
 * @重要修改备注 
 * 
 */
@Service
public class DictServiceImpl extends BaseService implements DictService {
	/**日志对象**/
	private static Logger logger = Logger.getLogger(DictServiceImpl.class);
	/**************实现类  其他对象 引用  开始***********************/
	/**应用数据库操作对象**/
	@Autowired
	private DictMapper dictMapper;
	
	/**************实现类  其他对象 引用  结束***********************/
	/**
	 * 查询所有从字典
	 * @param params 查询参数
	 * @param page 分页信息
	 * @param loginUser 登录用户
	 * @return
	 */
	@CacheConfig(key="dictList",query=true,paramsSize=2,expire=1800)
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public PageDto<Dict> queryDict(Dict params, PageDto<Dict> page, LoginUser loginUser) {
		DictExample example = new DictExample();
		Criteria criteria =  example.createCriteria();
		if(!loginUser.isSuperManager()){
			criteria.andTenantIdEqualTo(loginUser.getTenantId());
		}
		if(StrUtil.isNotBlank(params.getTypeId())){
			criteria.andTypeIdEqualTo(params.getTypeId());
		}
		criteria.andIsDeleteEqualTo(DeleteEnum.USE.getValue());
		this.setExamplePage(example, page);
		page.setTotal(dictMapper.countByExample(example));
		page.setRecords(dictMapper.selectByExample(example));
		return page;
	}
	
	 /**
     * 逻辑删除 字典数据
     * @param id
     * @param loginUser
     * @return
     */
	
	@CacheConfig(key="dict",paramsSize=1,delete=true, clearKey="dictList")
	@Transactional
	public Result<Object> deleteDict(String id, LoginUser loginUser) {
		Result<Object> result = null;
		result = new Result<Object>(0,SuccessMsg.OP_SUCCESS);
		Dict record = new Dict();
		record.setDictId(id);
		record.setIsDelete(DeleteEnum.DELETE.getValue());
		this.setUserForUpdate(record, loginUser);
		int opCount = dictMapper.updateByPrimaryKeySelective(record);
		if(opCount != 1){
			logger.error("DictServiceImpl=>deleteDict is error");
			throw new BussinessException(-1, ErrorMsg.DELETE_ERROR);
		}
		return result;
	}
	
	/**
	 * 新增字典
	 * @param record
	 * @param user
	 * @return
	 */
	@Transactional
	@CacheConfig(paramsSize=1,add=true,id="dictId", clearKey="dictList")
	public Result<Object> saveDict(Dict entity, LoginUser loginUser) {
		//对象验证 
		/*****************验证开始************************/	
		FieldRule fieldRule = new FieldRule();
		fieldRule.addRule(RuleEnum.IS_NOT_NULL, String.class, "value","值")
		.addRule(RuleEnum.IS_NOT_NULL, String.class, "name","名称")
		.addRule(RuleEnum.IS_NOT_NULL, String.class, "typeId","字典ID");
		Result<Object> rs =	EntityValidate.validate(entity, fieldRule);
		if(!rs.codeSuccess())return rs;
		/******************验证结束*******************/
		entity.setTenantId(loginUser.getTenantId());
		entity.setDictId(UUIDUtil.getUUID());
		entity.setIsDelete(DeleteEnum.USE.getValue());
		this.setUserForAdd(entity, loginUser);
		//执行成功数量	
		int exeCount = dictMapper.insertSelective(entity);
		if(exeCount != 1)return ResultHelper.getError();
		return ResultHelper.getSuccess();
	}
	
	/**
	 * 修改字典
	 * @param record
	 * @param user
	 * @return
	 */
	
	@CacheConfig(key="dict",paramsSize=1,update=true,id="dictId", clearKey="dictList")
	@Transactional
	public Result<Object> updateDict(Dict record, LoginUser loginUser) {
		Result<Object> result = null;
		result = new Result<Object>(0,SuccessMsg.OP_SUCCESS);
		this.setUserForUpdate(record, loginUser);
		int opCount = dictMapper.updateByPrimaryKeySelective(record);
		if(opCount != 1){
			logger.error("DictServiceImpl=>updateDict is error");
			throw new BussinessException(-1, ErrorMsg.UPDATE_ERROR);
		}
		return result;
	}
	
	/**
	 * 通过字典类型查询
	 * @param menuId
	 * @return
	 */
	@CacheConfig(key="dictList",paramsSize=1,query=true,expire=24*60*60)
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<Dict> queryDictsByDictType(String typeId) {
		Dict record = new Dict();
		record.setTypeId(typeId);
		record.setIsDelete(DeleteEnum.USE.getValue());
		return dictMapper.selectByRecord(record);
	}

	@CacheConfig(key="dict",paramsSize=1,query=true,expire=1800)
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public Dict queryDict(String id, LoginUser user) {
		return dictMapper.selectByPrimaryKey(id);
	}
	
	
	
	
}
